package com.xuxin.baby.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;

import org.jetbrains.annotations.NotNull;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by xu_xin on 2018/8/1 0019.
 * 倒计时60秒
 */
public class CountDown extends SpecialTextView {
    private Timer timer;
    private TimerTask task;
    private long duration = 60000;
    private long temp_duration = 60000;

    public CountDown(Context context) {
        super(context);
    }

    public CountDown(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setTime(long duration) {
        this.duration = duration;
    }

    public Boolean startTimer() {
        if (null != timer && null != task) {
            return false;
        }
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(0);
            }
        };
        timer.schedule(task, 0, 1000);
        return true;
    }

    private void stopTimer() {
        temp_duration = duration;
        if (task != null) {
            task.cancel();
            task = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private final Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NotNull Message message) {
            String msg = temp_duration / 1000 + "秒后获取";
            setText(msg);
            temp_duration -= 1000;
            if (temp_duration < 0) {
                setText("获取动态密码");
                stopTimer();
            }
            return false;
        }
    });
}